import React, { Component } from 'react';
import CommentInput from './CommentInput'
import CommentList from './CommentList'
import './commentapp.css'
class CommentApp extends Component{
  constructor(){
    super()
    this.state = {
      comments: []
    }
  }

  componentDidMount(){
    if(localStorage.getItem('comments')){
      this.setState({
        comments: JSON.parse(localStorage.getItem('comments'))
      })
    }
  }

  render(){
    return (
      <div className="comment-app">
        <CommentInput onSubmit={this.getComment.bind(this)}></CommentInput>
        <CommentList comments={this.state.comments} onDelete={this.deleteComment.bind(this)}></CommentList>
      </div>
    )
  }

  getComment(comment){
    let comments = this.state.comments
    comments.push(comment)
    this.setState({
      comments: comments
    })
    localStorage.setItem('comments',JSON.stringify(comments))
    console.log(this.state.comments)
  }

  deleteComment(index){
    let comments = this.state.comments
    comments.splice(index, 1)
    this.setState({
      comments: comments
    })
    localStorage.setItem('comments',JSON.stringify(comments))
  }
}

export default CommentApp